// pages/live-list/live-list.js
import * as API_Live from '../../api/live.js'
import * as API_Goods from '../../api/goods'
import { Foundation } from '../../ui-utils/index.js'
const app = getApp()
let log = require('../../log.js') // 引用上面的log.js文件

Page({
  /**
   * 页面的初始数据
   */
  data: {
    finshed: false, // 是否已经加载完毕
    liveList: [],
    width: 100,
    height: 30,
    fontSize: 15,
    color: "#ffffff",
    backgroundColor: '#2376e5',
    // 是否显示海报弹窗
    isShowPoster: false,
    posterImageUrl: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 获取分享时需要绑定的key
    app.getShareKey('plugin-private://wx2b03c6e691cd7370/pages/live-player-plugin', 'shareLive');
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.goLivePlay();
  },
  /**
    * @date 2020/09/28
    * @author wolfMan
    * @description {获取直播列表数据}
  */
  goLivePlay() {
    let _params = {
      'start': 0, // 起始拉取房间，start = 0 表示从第 1 个房间开始拉取
      'limit': 50 // 每次拉取的个数上限，不要设置过大，建议 100 以内
    };
    // 获取直播间信息，进入直播间
    API_Live.getLiveListInfo(_params).then(res => {
      let liveList = res || [];
      liveList = liveList.map(item => {
        let _status = item.live_status;
        if (_status === 101 || _status === 105 || _status === 106) {
          item.state = 1;
          item.stateText = '直播中';
          item.stateBack = 'back-red';
        } else if (_status === 102) {
          item.state = 2;
          item.stateText = '预告';
          item.stateBack = 'back-blue';
          item.startTime = Foundation.unixToDate(item.start_time, 'MM月dd日 hh:mm');
        } else if (_status === 103) {
          item.state = 3;
          item.stateText = '回放';
          item.stateBack = 'back-yellow';
        };
        if (item.state) {
          return item;
        };  
      });
      this.setData({
        finshed: true,
        liveList
      });
    }).catch(() => {
      this.setData({
        finshed: true
      });
    });
  },
  // 进入直播间
  goRoom(e) {
    let { room } = e.currentTarget.dataset;
    wx.navigateTo({
      url: `plugin-private://wx2b03c6e691cd7370/pages/live-player-plugin?room_id=${room}`
    });
  },
  // 监听订阅事件用于获取订阅状态
  onSubscribe(e) {
    console.log('房间号：', e.detail.room_id)
    console.log('订阅用户openid', e.detail.openid)
    console.log('是否订阅', e.detail.is_subscribe)
  },
  // 分享
  goShare(e) {
    if (!app.isLogin()) return
    wx.showLoading({
      title: '海报生成中...',
      icon: 'loading',
      duration: 8000
    });
    let { room } = e.currentTarget.dataset;
    let _posterData = {
      start_time: Foundation.unixToDate(room.start_time, 'MM月dd日 hh:mm'),
      name: room.name,
      share_img: room.share_img,
      sun_code_url: ''
    };
    let _shareKey = wx.getStorageSync('shareLive') || '';
    let _params = {
      'page_type': 0, // 1:商品详情；2:微页面；0:无额外数据请求
      'page_path': 'pages/leader/index/index',
      'scene': `${room.roomid}&${_shareKey}`
    };
    // 获取海报需要显示的信息
    API_Goods.getSunCode(_params).then(res => {
      let { sun_code_url } = res;
      if (sun_code_url && sun_code_url.indexOf('http:') > -1) {
        sun_code_url = `https:${sun_code_url.split('http:')[1]}`;
      };
      _posterData.sun_code_url = sun_code_url;
      this.createNewImg(_posterData);
    });
  },
  // 将canvas转换为图片保存到本地，然后将图片路径传给image图片的src
  createNewImg(posterData) {
    const that = this;
    let logoUrl = '';
    let codeUrl = '';
    let goodsUrl = '';
    const { share_img, sun_code_url, name, start_time } = posterData;
    let _urlArr = [
      {
        url: 'https://localhost/images/logo-circle.png',
        type: 1
      },
      {
        url: sun_code_url,
        type: 2
      },
      {
        url: share_img,
        type: 3
      }
    ];
    _urlArr.forEach(urlItem => {
      if (urlItem.url && urlItem.url.indexOf('http:') > -1) {
        urlItem.url = `https:${urlItem.url.split('http:')[1]}`;
      };
      wx.downloadFile({
        url: urlItem.url,
        success: function (res) {
          if (res.statusCode === 200) {
            const _urlNeed = res.tempFilePath;
            if (urlItem.type === 1) {
              logoUrl = _urlNeed;
            } else if (urlItem.type === 2) {
              codeUrl = _urlNeed;
            } else if (urlItem.type === 3) {
              goodsUrl = _urlNeed;
            };
            if (goodsUrl && codeUrl && logoUrl) {
              let context = wx.createCanvasContext('canvasPoster');
              context.setFillStyle("#ffffff");
              context.fillRect(0, 0, 340, 450);
              // 分享图
              context.drawImage(goodsUrl, 0, 0, 340, 272);
              // 太阳码
              context.drawImage(codeUrl, 208, 311, 96, 96);
              // 长按识别查看
              context.setFontSize(10),
              context.setFillStyle('#818181');
              context.fillText('长按识别发现精彩', 217, 428, 82);
              // 直播名
              context.setFontSize(15),
              context.setFillStyle('#000000');
              context.fillText(name, 17, 300, 260);
              // 直播时间
              let _time = `${start_time}开始`;
              context.setFontSize(15),
              context.setFillStyle('#e83227');
              context.fillText(_time, 17, 382, 260);
              // logo
              context.drawImage(logoUrl, 17, 413, 19, 19);
              // 公司名
              context.setFontSize(12),
              context.setFillStyle('#8b8b8b');
              context.fillText('门口淘本地生活', 42, 426, 260);
              // 绘图
              context.draw(false, setTimeout(() => {
                wx.canvasToTempFilePath({
                  canvasId: 'canvasPoster',
                  success: function (response) {
                    let tempFilePath = response.tempFilePath;
                    that.setData({
                      posterImageUrl: tempFilePath,
                      isShowPoster: true
                    });
                  },
                  fail: function (err) {
                    console.log(err);
                    log.error(err);
                  },
                  complete: function () {
                    wx.hideLoading()
                  }
                })
              }, 500));
            };
          };
        }
      });
    });
  },
  // 保存到相册
  savePoster() {
    var that = this;
    wx.saveImageToPhotosAlbum({
      filePath: that.data.posterImageUrl,
      success(res) {
        wx.showModal({
          content: '图片已保存到相册，赶紧晒一下吧~',
          showCancel: false,
          confirmText: '好的',
          confirmColor: '#333',
          success: function (res) {
            if (res.confirm) {
              console.log('用户点击确定');
              /* 关闭海报弹层 */
              that.closePoster();
            }
          }, fail: function (res) {
            console.log('保存失败')
          }
        })
      }
    })
  },
  // 关闭海报弹层
  closePoster() {
    this.setData({
      isShowPoster: false
    });
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.goLivePlay();
    // 停止下拉[回弹]
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})
